import { login, logout, getUserInfo, getUserProfile } from "@/api/user";
import { getToken, setToken, removeToken, setTimeStamp } from "@/utils/auth";
import { resetRouter } from "@/router";

const state = {
  token: getToken(),
  userInfo: {}
};

const mutations = {
  setToken(state, token) {
    state.token = token;
    setTimeStamp();
  },

  removeToken(state) {
    (state.token = null), removeToken();
  },

  setUserInfo(state, payload) {
    state.userInfo = payload;
  },

  removeUserInfo(state) {
    state.userInfo = {};
  }
};

const actions = {
  async login(context, data) {
    try {
      let res = await login(data);
      context.commit("setToken", res.data);
      setToken(res.data);
    } catch (error) {
      return Promise.reject(error);
    }
  },

  async getUserInfo(context) {
    let res = await getUserInfo();
    let res2 = await getUserProfile(res.data.userId);
    let allInfo = {
      ...res.data,
      ...res2.data
    };
    context.commit("setUserInfo", allInfo);
  },

  logout({ commit }) {
    commit("removeToken");
    commit("removeUserInfo");
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
